package net.coolskill.demo.springboot.util;

import java.util.concurrent.atomic.AtomicLong;

public class Context {

    private static final ThreadLocal<CtxHolder> CTX = new ThreadLocal<>();

    private static final AtomicLong requestTime = new AtomicLong(1);

    public static void execute(Executable target) {

        CtxHolder holder = CTX.get();

        try {
            CTX.set(new CtxHolder(requestTime.getAndIncrement()));
            target.execute();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (holder == null) {
                CTX.remove();
            } else {
                CTX.set(holder);
            }
        }
    }

    public static long getRequestId() {
        CtxHolder holder = CTX.get();
        return holder == null ? -1 : holder.getRequestId();
    }

    static class CtxHolder {

        private final long requestId;

        CtxHolder(long requestId) {
            this.requestId = requestId;
        }

        long getRequestId() {
            return requestId;
        }
    }
}
